package com.android.infantschool.util;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.android.infantschool.ui.activity.SplashActivity;

import java.lang.Thread.UncaughtExceptionHandler;

/**
 * 异常信息收集，报错crash日志
 */
public class CrashHandler implements UncaughtExceptionHandler {

    public static String TAG = "CrashHandler";
    private UncaughtExceptionHandler mDefaultHandler;// 系统默认的UncaughtException处理类
    private static CrashHandler instance = null;
    private Context mContext;

    public static CrashHandler getInstance() {
        if (instance == null) {
            synchronized (CrashHandler.class) {
                if (instance == null) {
                    instance = new CrashHandler();
                }
            }
        }
        return instance;
    }

    //初始化
    public void init(Context context) {
        mContext = context;
        // 获取系统默认的UncaughtException处理器
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        // 设置该CrashHandler为程序的默认处理器
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        Log.e(TAG, "捕捉到全局异常:" + ex.toString());
        if (ex != null && mDefaultHandler != null) {
            // 如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            // TODO: 2019/8/9 重启App
            reStartApp(mContext);
        }
    }

    /**
     * 重启应用程序
     *
     * @param context
     */
    public static void reStartApp(Context context) {
        Intent intent = new Intent(context, SplashActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());
    }

}